<template>
  <div class="main-page">
    <div class="goods-container">
      <div class="category-list">
        <ul>
          <li v-for="(cat, idx) in categories" :key="cat.id" :class="{active: idx===activeCategory}" @click="selectCategory(idx)">{{ cat.name }}</li>
        </ul>
      </div>
      <div class="goods-list">
        <div v-for="item in goods" :key="item.id" class="goods-item">
          <img :src="item.imageUrl" alt="商品图片" style="width: 100%; height: 120px; object-fit: cover;">
          <h4>{{ item.name }}</h4>
          <p>{{ item.description }}</p>
          <span>￥{{ item.price / 100 }}</span>
          <button @click="addToCart(item)">加入购物车</button>
        </div>
      </div>
    </div>
    <div class="bottom-nav">
      <router-link to="/main" exact>商品</router-link>
      <router-link to="/orders">我的订单</router-link>
      <router-link to="/profile">个人中心</router-link>
      <router-link v-if="isRider" to="/rider">骑手中心</router-link>
      <router-link v-if="isAdmin" to="/merchant">商家后台</router-link>
    </div>
    <div class="cart-area">
      <el-card class="cart-card" v-if="cart.length">
        <div slot="header">购物车</div>
        <el-table :data="cart" style="width: 100%">
          <el-table-column prop="name" label="商品名" width="120" />
          <el-table-column label="数量" width="120">
            <template slot-scope="scope">
              <el-button size="mini" @click="decreaseCart(scope.row)">-</el-button>
              {{ scope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column label="小计" width="80">
            <template slot-scope="scope">
              ￥{{ scope.row.price }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align:right;margin-top:10px;">总价：￥{{ cartTotal }}</div>
        <el-button type="primary" style="margin-top: 10px;" @click="handlePay">下单</el-button>
      </el-card>
      <div v-else class="cart-empty">购物车为空</div>
    </div>
  </div>
</template>

<script>
import { itemApi } from '@/utils/request'
import { cartApi } from '@/utils/request'
export default {
  name: 'Main',
  data() {
    return {
      categories: [],
      goods: [],
      activeCategory: 0,
      cart: [],
      userInfo: null
    }
  },
  computed: {
    isAdmin() {
      return this.userInfo && this.userInfo.type === 2;
    },
    isRider() {
      return this.userInfo && this.userInfo.type === 1;
    },
    cartTotal() {
      return this.cart.reduce((sum, item) => sum + item.price, 0)
    }
  },
  created() {
    this.fetchCategories();
    this.fetchCart();
    this.loadUserInfo();
  },
  methods: {
    fetchCategories() {
      itemApi.getCategoryGoods().then(res => {
        const categoryMap = {0: '零食', 1: '泡面', 2: '饮料'};
        this.categories = Object.keys(res).map(key => ({
          id: String(key),
          name: categoryMap[String(key)] || `分类${key}`,
          items: res[key]
        }));
        if (this.categories.length) {
          this.selectCategory(0)
        }
      }).catch(err => {
        console.error('获取分类失败:', err);
      });
    },
    selectCategory(idx) {
      this.activeCategory = idx
      const category = this.categories[idx]
      if (!category) return
      this.goods = category.items || []
    },
    fetchCart() {
      cartApi.getCartGoods().then(res => {
        const cartRaw = res
        this.cart = cartRaw.map(cartItem => ({
          id: cartItem.itemId,
          name: cartItem.itemName,
          price: cartItem.price / 100, // 将分转换为元
          amount: cartItem.quantity
        }))
      })
    },
    addToCart(item) {
      console.log('加入购物车，商品信息:', item);
      cartApi.increaseCart({ itemId: item.id, amount: 1 }).then(() => {
        this.fetchCart()
      }).catch(err => {
        console.error('加入购物车失败:', err);
      })
    },
    decreaseCart(item) {
      cartApi.decreaseCart({ itemId: item.id, amount: 1 }).then(() => {
        this.fetchCart()
      }).catch(err => {
        console.error('减少购物车失败:', err);
      })
    },
    handlePay() {
      this.$router.push({
        path: '/payment',
        query: {
          totalPrice: this.cartTotal,
          itemId: this.cart[0].id,
          itemName: this.cart[0].name,
          currentPrice: this.cart[0].price,
          quantity: this.cart[0].amount
        }
      })
    },
    loadUserInfo() {
      const storedUserInfo = localStorage.getItem('userInfo');
      if (storedUserInfo) {
        this.userInfo = JSON.parse(storedUserInfo);
        console.log('用户信息:', this.userInfo);
      }
    }
  }
}
</script>

<style scoped>
.main-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.goods-container {
  flex: 1;
  display: flex;
  background: #fafafa;
}
.category-list {
  width: 100px;
  background: #f5f5f5;
  border-right: 1px solid #eee;
}
.category-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.category-list li {
  padding: 16px 8px;
  cursor: pointer;
}
.category-list li.active {
  background: #42b983;
  color: #fff;
}
.goods-list {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.goods-item {
  width: 160px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 12px;
  box-shadow: 0 2px 8px #f0f1f2;
}
.bottom-nav {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 54px;
  background: #fff;
  border-top: 1px solid #eee;
}
.bottom-nav a {
  flex: 1;
  text-align: center;
  color: #666;
  font-size: 16px;
  padding: 10px 0;
  text-decoration: none;
}
.bottom-nav a.router-link-exact-active {
  color: #42b983;
  font-weight: bold;
}
.cart-area {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 54px;
  background: #fff;
  box-shadow: 0 -2px 8px #f0f1f2;
  z-index: 100;
  padding: 10px 16px;
}
.cart-card {
  width: 100%;
}
.cart-empty {
  text-align: center;
  color: #aaa;
  padding: 16px 0;
}
</style>